package com.fortune.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
 * 
 * @author ran
 *
 */
public class PinYinUtil {
	private static Logger logger = LoggerFactory.getLogger(PinYinUtil.class);
	
	private static HanyuPinyinOutputFormat format;
	static {
		format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);
	}
	/**
	 * cnCharacters必须是纯汉字字符串，有非汉字字符则返回null
	 * @param cnCharacters
	 * @return
	 */
	public static String getInitials(String cnCharacters) {
		StringBuffer sb = new StringBuffer();
		char[] cns = cnCharacters.toCharArray();
		for (char c : cns) {
			String[] pinyins;
			try {
				pinyins = PinyinHelper.toHanyuPinyinStringArray(c, format);
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				logger.error("字符串" + cnCharacters + "转换成拼音异常", e);
				return null;
			}
			if (pinyins==null || pinyins.length==0) {
				logger.error("字符串中不能有非汉字字符！");
				return null;
			}
			sb.append(pinyins[0].substring(0, 1));
		}
		return sb.toString();
	}
}
